package com.bigdata.core.example

import org.apache.spark.util.LongAccumulator
import org.apache.spark.{SparkConf, SparkContext}

/**
 * 累加器
 */
object AccumulatorTest {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local")
    conf.setAppName("accumulator")
    val sc = new SparkContext(conf)
    sc.setLogLevel("error")

    val accumulator: LongAccumulator = sc.longAccumulator("My Accumulator")
    var num = 1
    val lines = sc.textFile("data/words", 4)
    println(lines.getNumPartitions)
    val trans = lines.map(line => {
      accumulator.add(1)
      num = num + 1
      line
    })
    // action 算子触发job执行
    trans.collect()

    println(s"accumulator value is ${accumulator.value}")
    println(s"num is ${num}")
  }
}